package com.appsky.drift.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.appsky.drift.R;
import com.appsky.drift.adapter.NearbyPersonListAdapter;
import com.appsky.drift.api.AppSkyApp;
import com.appsky.drift.api.DLog;
import com.appsky.drift.api.JsonFactory;
import com.appsky.drift.api.UserInfo;
import com.appsky.drift.api.Utils;
import com.appsky.drift.dialog.AboutDialog;
import com.appsky.drift.dialog.EnterNickAndSexDialog;
import com.appsky.drift.service.DriftService;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DriftActivity extends MapActivity {

	private static final int QUIT_DIALOG = 0;

	private MapView mainMap = null;

	private AppSkyApp app;

	private Button createRoomButton;

	private Button refreshButton;

	private Button joinRoomButton;

	private RelativeLayout nearbyPersonLayout;

	private TextView nearbyPersonButton;

	private TextView awayButton;

	private ListView nearbyPersonListView;

	private ProgressDialog progressDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		app = (AppSkyApp) getApplication();

	}

	@Override
	protected void onStart() {
		initView();
		initMapView();
		if (!app.isLogin()) {
			initLoginHandler();
			Intent serviceIntent = new Intent(DriftActivity.this,
					DriftService.class);
			startService(serviceIntent);
		} else {
			DLog.i("已经登录过了！");
		}
		super.onStart();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuItem changeInfo = menu.add(0, 0, 0, R.string.set_user_info);
		changeInfo.setIcon(R.drawable.ic_edit);

		MenuItem about = menu.add(0, 1, 0, R.string.about);
		about.setIcon(R.drawable.ic_about);
		
		MenuItem quit = menu.add(0, 2, 0, R.string.exit);
		quit.setIcon(R.drawable.ic_quit);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			new EnterNickAndSexDialog(this).show();
			break;
		case 1:
			new AboutDialog(DriftActivity.this).show();
			break;
		case 2:
			showDialog(QUIT_DIALOG);
			break;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO 检测是否还在飘
		if (progressDialog != null) {
			if (progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
		}
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showDialog(QUIT_DIALOG);
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case QUIT_DIALOG:
			return new AlertDialog.Builder(DriftActivity.this)
					.setIcon(R.drawable.ic_interrogative)
					.setTitle(R.string.sure_quit_app)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									stopService(new Intent(DriftActivity.this,
											DriftService.class));
									finish();
								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		default:
			return super.onCreateDialog(QUIT_DIALOG);
		}
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private void initView() {
		initButtons();
		initAnimationButtons();
	}

	private void initButtons() {
		createRoomButton = (Button) findViewById(R.id.create_room);
		createRoomButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				JsonFactory jsonFactory = JsonFactory.getFactory();
				JSONObject json = jsonFactory.makeCreateRoomJson(app.myInfo
						.getUserId());
				Intent intent = new Intent(Utils.ACTION_SEND_MESSAGE);
				intent.putExtra("json", json.toJSONString());
				sendBroadcast(intent);
				app.myInfo.setRoomId(app.myInfo.getUserId());
				Intent activityIntent = new Intent(DriftActivity.this,
						ChatMainActivity.class);
				startActivity(activityIntent);
			}
		});

		refreshButton = (Button) findViewById(R.id.refresh_button);
		refreshButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				initMapView();
			}
		});

		joinRoomButton = (Button) findViewById(R.id.join_room_button);
		joinRoomButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showNearbyPersonList();
			}
		});

	}

	private void initAnimationButtons() {

		nearbyPersonButton = (TextView) findViewById(R.id.nearby_person_button);
		nearbyPersonButton.setVisibility(View.VISIBLE);
		nearbyPersonButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showNearbyPersonList();
			}
		});

		nearbyPersonLayout = (RelativeLayout) findViewById(R.id.nearby_person_layout);
		nearbyPersonLayout.setVisibility(View.GONE);
		nearbyPersonListView = (ListView) findViewById(R.id.person_list);

		awayButton = (TextView) findViewById(R.id.away_button);
		awayButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Animation animation = AnimationUtils.loadAnimation(
						DriftActivity.this, R.anim.push_top_out);
				nearbyPersonLayout.startAnimation(animation);
				nearbyPersonLayout.setVisibility(View.GONE);
				nearbyPersonButton.setVisibility(View.VISIBLE);
			}
		});
	}

	private void initLoginHandler() {
		app.loginHandler = new LoginHandler();
	}

	private class LoginHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Utils.START_PROGRESS) {
				progressDialog = new ProgressDialog(DriftActivity.this);
				progressDialog.setMessage("正在登录，请稍等...");
				progressDialog.setCancelable(true);
				progressDialog.show();
			} else {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
				}
				messageProcess(msg.what);
			}
		}

		private void messageProcess(int what) {
			switch (what) {
			case Utils.REGISTER_SUCCESS:// 如果是注册成功，要在本地储存返回的newId
//				SharedPreferences globalPref = getSharedPreferences(
//						Utils.PREF_GLOBAL, MODE_PRIVATE);
//				Editor editor = globalPref.edit();
//				editor.putInt(getString(R.string.pref_userId),
//						app.myInfo.getUserId());
//				editor.commit();
				Toast.makeText(DriftActivity.this, "注册成功！", Toast.LENGTH_SHORT)
						.show();
				DLog.i("注册成功！！");
				initMapView();
				break;
			case Utils.LOGIN_SUCCESS:
				Toast.makeText(DriftActivity.this, "登录成功！", Toast.LENGTH_SHORT)
						.show();
				DLog.i("登录成功！！");
				initMapView();
				break;
			case Utils.LOGIN_TIMEOUT:
				Toast.makeText(DriftActivity.this, "登录超时，请重试！",
						Toast.LENGTH_LONG).show();
				DLog.i("登录超时！");
				break;
			case Utils.LOGIN_ERROR:
				Toast.makeText(DriftActivity.this, "登录失败，请重试！",
						Toast.LENGTH_LONG).show();
				DLog.i("登录异常！");
				break;

			}
		}
	}

	private void initMapView() {
		if (mainMap == null) {
			mainMap = (MapView) findViewById(R.id.main_map);
			mainMap.setSatellite(false);
			mainMap.setTraffic(true);
			mainMap.setStreetView(false);
		}

		setMapView();
	}
	
	private void setMapView() {
		GeoPoint point = new GeoPoint(app.myInfo.getLatitude(),
				app.myInfo.getLongitude());

		List<Overlay> mapOverlays = mainMap.getOverlays();

		Collection<UserInfo> infoList = app.myInfo
				.getNearbyPersonListFromHashMap();

		MyPlaceOverlay myPlace = new MyPlaceOverlay(point);

		mapOverlays.add(myPlace);
		mapOverlays.addAll(loadPersonInfo(infoList));

		MapController mapController = mainMap.getController();
		mapController.animateTo(point);
		mapController.setZoom(7);
	}

	private class MyPlaceOverlay extends Overlay {

		private GeoPoint geoPoint = null;

		public MyPlaceOverlay(GeoPoint geoPoint) {
			this.geoPoint = geoPoint;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection projection = mapView.getProjection();
			projection.toPixels(geoPoint, point);
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.my_place);
			canvas.drawBitmap(bitmap, point.x, point.y, null);
		}

	}

	private class OtherPlaceOverlay extends Overlay {

		private GeoPoint geoPoint = null;

		private UserInfo info = null;

		public OtherPlaceOverlay(GeoPoint geoPoint, UserInfo info) {
			this.geoPoint = geoPoint;
			this.info = info;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection projection = mapView.getProjection();
			projection.toPixels(geoPoint, point);
			Bitmap bitmap = null;
			if (info.isRoomOwner()) {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.room_owner_place);
			} else if (info.isDrifting()) {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.drifting_person_place);
			} else {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.room_person_place);
			}
			canvas.drawBitmap(bitmap, point.x, point.y, null);

			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setTextSize(20);
			paint.setTextAlign(Align.CENTER);
			canvas.drawText(info.getNick(), point.x, point.y - 10, paint);
		}

	}

	private void showNearbyPersonList() {
		if (nearbyPersonButton != null) {
			nearbyPersonButton.setVisibility(View.GONE);
			Collection<UserInfo> userList = new ArrayList<UserInfo>();
			userList.addAll(app.myInfo.getNearbyPersonListFromHashMap());
			BaseAdapter nearbyAdapter = new NearbyPersonListAdapter(
					DriftActivity.this, (ArrayList<UserInfo>) userList);
			nearbyPersonListView.setAdapter(nearbyAdapter);
			nearbyPersonLayout.setVisibility(View.VISIBLE);
			Animation animation = AnimationUtils.loadAnimation(
					DriftActivity.this, R.anim.push_top_in);
			nearbyPersonLayout.startAnimation(animation);
		}
	}

	private Collection<Overlay> loadPersonInfo(Collection<UserInfo> infoList) {
		Collection<Overlay> result = new ArrayList<Overlay>();
		Iterator<UserInfo> iterator = infoList.iterator();
		while (iterator.hasNext()) {
			UserInfo info = iterator.next();
			GeoPoint point = new GeoPoint(info.getLatitude(),
					info.getLongitude());
			OtherPlaceOverlay other = new OtherPlaceOverlay(point, info);
			result.add(other);
		}
		return result;
	}
}